﻿namespace PlayListBundler
{
    using System;
    using System.Windows.Forms;
    using System.IO;

    /// <summary>The main form of PlayListBundler.</summary>
    public partial class MainForm : Form
    {
        const string FolderText = "Please choose directory.";
        Manager manager;
        int oldSelectedIndex;
        bool mouseDown;
        bool allowUserTextInput;

        /// <summary>
        /// Initializes a new instance of the <see cref="MainForm"/> class.
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            manager = new Manager();
        }

        #region Drag and Drop events
        private void MainForm_DragOver(object sender, DragEventArgs dea)
        {
            if (dea.Data.GetDataPresent(DataFormats.FileDrop))
                dea.Effect = DragDropEffects.Move;
        }

        private void MainForm_DragDrop(object sender, DragEventArgs dea)
        {
            if (dea.Data.GetDataPresent(DataFormats.FileDrop))
            {
                string[] files = (string[])dea.Data.GetData(DataFormats.FileDrop);
                AddMp3s(files);
            }
        }
        #endregion Drag and Drop events

        #region Click and Button events
        private void ChooseFolderBtn_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            int nr = 80;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string path = dialog.SelectedPath;
                if (path.Length > nr)
                {
                    int start = path.Length - nr + 3;
                    FolderLabel.Text = "..." + path.Substring(start);
                }
                else
                    FolderLabel.Text = path;
            }
        }

        private void CopyBtn_Click(object sender, EventArgs e)
        {
            if (FolderLabel.Text == FolderText)
            {
                MessageBox.Show(FolderText);
                return;
            }

            ProgressBarForm form = new ProgressBarForm();
            form.ProgressBar.Maximum = manager.Count - 1;
            form.Show();
            form.TopMost = true;
            manager.Copy(FolderLabel.Text, form);
        }
        #endregion Click and Button events

        private void RefillManagerItems()
        {
            string[] items = new string[OrigFiles.Items.Count];
            OrigFiles.Items.CopyTo(items, 0);
            manager.ReFill(items);
        }

        private void RefillOrigFilesAndNewFilesList()
        {
            OrigFiles.Items.Clear();
            
            NewFilesRichTextBox.Text = "";
            for (int i = 0; i < manager.Count; i++)
            {
                OrigFiles.Items.Add(manager.Files.OrigName[i]);
                NewFilesRichTextBox.Text = NewFilesRichTextBox.Text + 
                                           manager.Files.NewName[i] + " \n";
            }
        }

        private void AddMp3s(string[] NewFiles)
        {
            //NewFiles = Pattern.GetFilesWithExtension(NewFiles, "mp3");
            NewFiles = Pattern.GetFilesWithExtension(NewFiles, "jpg");
            manager.Add(NewFiles);
            RefillOrigFilesAndNewFilesList();
        }

        private void OrigFiles_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Console.WriteLine("index allg.ch.");
            if (mouseDown && 
                OrigFiles.SelectedIndex != -1)
            {
                object obj = OrigFiles.Items[oldSelectedIndex];
                int newIndex = OrigFiles.SelectedIndex;
                OrigFiles.Items.RemoveAt(oldSelectedIndex);
                OrigFiles.Items.Insert(newIndex, obj);

                RefillManagerItems();
                RefillOrigFilesAndNewFilesList();

                mouseDown = false;
                OrigFiles.SelectedIndex = newIndex;
                
             //   Console.WriteLine("index ch.");
            }
        }

        private void OrigFiles_MouseDown(object sender, MouseEventArgs e)
        {
            mouseDown = true;
            oldSelectedIndex = OrigFiles.SelectedIndex;
        }

        private void OrigFiles_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete && OrigFiles.SelectedIndex != -1)
            {
                int selectedIndex = OrigFiles.SelectedIndex;
                OrigFiles.Items.RemoveAt(selectedIndex);
                RefillManagerItems();
                RefillOrigFilesAndNewFilesList();
                if (selectedIndex > 0)
                    OrigFiles.SelectedIndex = selectedIndex - 1;
            }
            else if (e.KeyData == (Keys.Control | Keys.N))
                TsBtnNumber_Click(null, null);
        }

        private void TsBtnNumber_Click(object sender, EventArgs e)
        {
            manager.WithTrackNumber = !manager.WithTrackNumber;
            RefillManagerItems();
            RefillOrigFilesAndNewFilesList();
        }

        private void NewFilesRichTextBox_TextChanged(object sender, EventArgs e)
        {
            if (!allowUserTextInput)                      
                return;
            else
            {                
                string[] items = NewFilesRichTextBox.Text.Split(new string[1] { " \n" }, 
                                 StringSplitOptions.RemoveEmptyEntries);
                manager.Rename(items);                
            }            
        }

        private void TsBtnAllowUserInput_CheckedChanged(object sender, EventArgs e)
        {
            if (((ToolStripButton)sender).Checked)
            {
                OrigFiles.SelectionMode = SelectionMode.None;
                NewFilesRichTextBox.ReadOnly = false;
            }
            else
            {
                if (MessageBox.Show(
                    "Are you sure? Your manual changes will be discarded.",
                    "Are you sure?",
                    MessageBoxButtons.OKCancel) == DialogResult.Cancel)
                {
                    ((ToolStripButton)sender).Checked = true;
                    return;                
                }                
                OrigFiles.SelectionMode = SelectionMode.One;
                NewFilesRichTextBox.ReadOnly = true;
                oldSelectedIndex = 0; // Just to avoid oldSelectedIndex = -1
                mouseDown = true;     // Just to allow index changes event
                if (OrigFiles.Items.Count != 0)
                    OrigFiles.SetSelected(0, true);
            }
            allowUserTextInput = !allowUserTextInput;
        }

        // Creates the directories cd01-cd10.
        private void TsBtnCreateDirectories_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            string exists = "";

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                string path = dialog.SelectedPath;
                // CD01-09
                for (int i = 0; i < 10; i++)
                    if (Directory.Exists(path + @"\CD0" + i))
                        exists = exists + "\nCD0" + i;
                    else
                        Directory.CreateDirectory(path + @"\CD0" + i);
                //CD10
                if (Directory.Exists(path + @"\CD" + 10))
                    exists = exists + "\nCD" + 10;
                else
                    Directory.CreateDirectory(path + @"\CD" + 10);

                MessageBox.Show(
                    "Directories created. Already exists (not recreated): " + exists, 
                    "Directories created.");
            }
        }

        private void TsBtnReset_Click(object sender, EventArgs e)
        {
            manager.RemoveAll();
            RefillOrigFilesAndNewFilesList();
            FolderLabel.Text = FolderText;
        }

    }
}
